# -*- coding: utf-8 -*-
# streamlit_doctor.py
import sys
import os
import subprocess
import importlib.util

def check_streamlit_deep():
    print("🔬 Streamlit深度检查")
    print("-" * 40)
    
    # 1. 检查streamlit模块是否可导入
    try:
        import streamlit
        print(f"✅ Streamlit模块导入成功")
        print(f"   版本: {streamlit.__version__}")
        print(f"   路径: {streamlit.__file__}")
    except Exception as e:
        print(f"❌ Streamlit导入失败: {e}")
        return False
    
    # 2. 检查streamlit的核心依赖
    dependencies = ['tornado', 'click', 'toml', 'typing_extensions']
    for dep in dependencies:
        try:
            __import__(dep)
            print(f"✅ {dep} 正常")
        except Exception as e:
            print(f"❌ {dep} 有问题: {e}")
    
    # 3. 检查streamlit命令
    try:
        result = subprocess.run([sys.executable, '-c', 
                               'import streamlit.web.cli as cli; print("CLI模块正常")'], 
                               capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            print("✅ Streamlit CLI模块正常")
        else:
            print(f"❌ CLI模块有问题: {result.stderr}")
    except Exception as e:
        print(f"❌ CLI检查失败: {e}")
    
    # 4. 尝试创建streamlit应用实例
    try:
        from streamlit.web.server import Server
        from streamlit.web.server.server import start_listening
        print("✅ Streamlit核心组件可用")
    except Exception as e:
        print(f"❌ 核心组件有问题: {e}")
    
    return True

def manual_streamlit_start():
    print("\n🚀 手动启动Streamlit")
    print("-" * 40)
    
    try:
        # 尝试手动启动streamlit
        print("正在尝试手动启动...")
        
        # 创建测试脚本内容
        script_content = """
import streamlit as st
st.write("手动启动成功！")
"""
        
        # 写入临时文件
        with open("manual_test.py", "w") as f:
            f.write(script_content)
        
        # 尝试不同的启动方式
        start_commands = [
            [sys.executable, "-m", "streamlit", "run", "manual_test.py"],
            ["streamlit", "run", "manual_test.py"],
            [sys.executable, "-c", "import streamlit.web.cli as cli; cli.main(['run', 'manual_test.py'])"]
        ]
        
        for i, cmd in enumerate(start_commands, 1):
            print(f"\n尝试方法 {i}: {' '.join(cmd)}")
            try:
                # 只检查命令是否能执行，不等待完成
                process = subprocess.Popen(cmd, 
                                         stdout=subprocess.PIPE, 
                                         stderr=subprocess.PIPE,
                                         text=True)
                
                # 等待2秒看是否有immediate错误
                try:
                    stdout, stderr = process.communicate(timeout=3)
                    if process.returncode == 0:
                        print("✅ 命令执行成功")
                    else:
                        print(f"❌ 命令执行失败: {stderr}")
                except subprocess.TimeoutExpired:
                    print("✅ 命令正在执行中（这是好现象！）")
                    process.kill()
                    print("💡 请尝试手动运行此命令")
                    break
                    
            except FileNotFoundError:
                print(f"❌ 命令不存在: {cmd[0]}")
            except Exception as e:
                print(f"❌ 执行失败: {e}")
        
        # 清理临时文件
        try:
            os.remove("manual_test.py")
        except:
            pass
            
    except Exception as e:
        print(f"❌ 手动启动失败: {e}")

if __name__ == "__main__":
    print("🩺 Streamlit医生 - 专业诊断工具")
    print("=" * 50)
    
    if check_streamlit_deep():
        manual_streamlit_start()
    
    print("\n📋 诊断完成！请将结果发给我进一步分析。")
